package com.vvvtimes.demo.util;

import cn.hutool.http.webservice.SoapClient;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPFault;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SoapClientManager {

    private static final String WBSERVICE_NS = "http://msdn.itellyou.cn/";

    private static final String WBSERVICE_URL = "http://msdn.itellyou.cn/hash.asmx";

    private static SoapClientManager mInstance;

    private SoapClient soapClient;

    private SoapClientManager() {
        soapClient = SoapClient.create(WBSERVICE_URL);
    }

    public static SoapClientManager getInstance() {
        if (mInstance == null) {
            synchronized (SoapClientManager.class) {
                if (mInstance == null) {
                    mInstance = new SoapClientManager();
                }
            }
        }
        return mInstance;
    }

    public String execute(String methodName, String paramName, String paramVal) {

        try {
            soapClient.setMethod(methodName, WBSERVICE_NS)
                    .setParam(paramName, paramVal);

            SOAPBody soapBody = soapClient.sendForMessage().getSOAPBody();
            SOAPFault fault = soapBody.getFault();
            if (!ObjectUtils.isEmpty(fault) && fault.hasDetail()) {
                String faultCode = fault.getFaultCode();
                String faultString = fault.getFaultString();
                log.error("faultCode={}", faultCode);
                log.error("faultString={}", faultString);

            } else {
                String textContent = soapBody.getTextContent();
                log.info("textContent={}", textContent);
                return textContent;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;

    }

    public static void main(String[] args){
        String execute = SoapClientManager.getInstance().execute("OnlineValidateV2", "sha1", "B89FDC0E10F01D74AAB91C0C0B0D3A9AEDEFF667");
        log.info(execute);
    }
}
